package com.example.check.validator;

import com.example.check.Password;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;

/**
 * 自定义密码校验器
 *
 * @author cloudgyb
 * @since 2021/8/8 13:32
 */
public class PasswordValidator implements ConstraintValidator<Password, CharSequence> {
    private Pattern pattern;

    /*
     * 只需要实现initialize和isValid方法即可！
     * isValid方法根据用户指定的正则表达式去校验密码。
     * */

    /**加载校验规则*/
    @Override
    public void initialize(Password constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
        this.pattern = Pattern.compile(constraintAnnotation.regexp());
    }

    /**开始校验*/
    @Override
    public boolean isValid(CharSequence value, ConstraintValidatorContext context) {
        if (value == null || value.length() == 0) {
            return false;
        }
        return this.pattern.matcher(value).matches();
    }
}
